package me.liuyu.ymall.config.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author liuyu E-mail: liuyu2783@163.com
 * @Date 2018/5/26 14:09
 * @Descrption
 * @Modified By
 */
public class YmallZuulFilter extends ZuulFilter {

    private Logger logger = LoggerFactory.getLogger(YmallZuulFilter.class);

    /**
     * 返回一个字符串代表过滤器的类型
     * pre表示被路由之前
     */
    @Override
    public String filterType() {
        logger.info("pre");
        return "pre";
    }

    /**
     * 过滤顺序
     */
    @Override
    public int filterOrder() {
        logger.info("0");
        return 0;
    }

    /**
     * 是否执行该过滤器，true代表需要过滤
     * @return
     */
    @Override
    public boolean shouldFilter() {
        logger.info("true");
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();

        logger.info("send {} request to {}", request.getMethod(), request.getRequestURL().toString());

        //获取传来的参数accessToken
        Object accessToken = request.getParameter("accessToken");
        if(accessToken == null) {
            logger.error("access token is empty");
            //过滤该请求，不往下级服务去转发请求，到此结束
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(401);
            ctx.setResponseBody("{\"result\":\"accessToken is empty!\"}");
            return null;
        }
        //如果有token，则进行路由转发
        logger.info("access token ok");
        //这里return的值没有意义，zuul框架没有使用该返回值
        return null;
    }
}
